package com.tjl.controller;

import com.tjl.model.Admin;
import com.tjl.model.User;
import com.tjl.service.Impl.AdminServiceImpl;
import com.tjl.service.Impl.UserServiceImpl;
import com.tjl.util.CodeMsg;
import com.tjl.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping
public class LoginController {

    @Autowired
    private UserServiceImpl ServiceImpl;

    @Autowired
    private AdminServiceImpl adminService;


    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping ("/login")
    public CodeMsg login(@RequestBody User user){

        if (user.getUsername().equals("") || user.getPassword().equals("")){
            return new CodeMsg(false,"输入不能为空");
        }
        User one = ServiceImpl.login(user);

        if (Objects.isNull(one)){
            return new CodeMsg(false);
        }
        String jwt = jwtUtils.createJwt(String.valueOf(one.getId()));
        return new CodeMsg(one,jwt);
    }

    @PostMapping ("/adminLogin")
    public CodeMsg adminlogin(@RequestBody Admin admin){

        if (admin.getUsername().length() < 1 || admin.getPassword().length() < 1){
            return new CodeMsg(false,"输入不能为空");
        }

        Admin one = adminService.login(admin);

        if (Objects.isNull(one)){
            return new CodeMsg(false);
        }

        String jwt = jwtUtils.createJwt(String.valueOf(one.getAid()));

        return new CodeMsg(one,jwt);
    }

}
